package main

import (
	"fmt"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v9"
	goredislib "github.com/redis/go-redis/v9"
	"sync"
	"time"
)

func main() {
	client := goredislib.NewClient(&goredislib.Options{
		Addr: "127.0.0.1:6379",
		//Password: "123321",
	})
	pool := goredis.NewPool(client)

	rs := redsync.New(pool)
	mutexname := "my-global-mutex"
	wg := &sync.WaitGroup{}
	gNun := 2
	wg.Add(gNun)
	for i := 0; i < gNun; i++ {
		go func() {
			defer wg.Done()
			mutex := rs.NewMutex(mutexname)
			fmt.Printf("a%d开始加锁", i)
			fmt.Println()
			if err := mutex.Lock(); err != nil {
				panic(err)
			}
			fmt.Printf("a%d加锁成功", i)
			fmt.Println()
			time.Sleep(3 * time.Second)
			if ok, err := mutex.Unlock(); !ok || err != nil {
				panic("unlock failed")
			}
			fmt.Println(" a", i, "解锁成功")
			fmt.Println()
		}()
	}
	wg.Wait()
}
